package com.chalk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.constant.SecurityConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.model.Member;
import com.chalk.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @date: 2019-04-02 上午 12:21
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
@Service
public class MemberDetailServiceImpl implements UserDetailsService {

    @Autowired
    private MemberService memberService;

    @Override
    public UserDetails loadUserByUsername(String username) throws ServiceException {
        Member member = memberService.selectOne(new EntityWrapper<Member>().eq("mobile_phone", username));
        if (member == null) {
            throw new ServiceException("用户" + username + "不存在");
        }
        //是否删除
        if (member.getIsDeleted().equals(CommonConstants.IsDeleted.DEL.getValue())) {
            throw new ServiceException("用户" + username + "已删除");
        }
        /* 权限业务 */
        Set<String> dbAuthsSet = new HashSet<>();
        /* 登录角色 */
        dbAuthsSet.add(SecurityConstants.ROLE_LOGIN);
        Collection<? extends GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        /* 构造security用户 */
        return new User(username, member.getPassword(), true,
                true, true, true, grantedAuthorities);
    }
}
